package pbx.service;


import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import pbx.model.Cdr;


@Stateless
public class CdrService {

	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	
	public Cdr save(Cdr cdr) {
		em.persist(cdr);
		return cdr;   
	}
	
	public Cdr update(Cdr cdr) {
		return em.merge(cdr);
	}


    public void changeBilledByMonth(Integer year, Integer month, Boolean status, Integer accountcode){
    
		String sql = "UPDATE Cdr e SET e.billed = null WHERE e.year=:year AND e.month=:month ";
		if(accountcode!=null){
			sql = sql + " AND e.accountcode=:accountcode ";
		}
		Query query = em.createQuery(sql);
		query.setParameter("year", year);
		query.setParameter("month", month);
		if(accountcode!=null){
			query.setParameter("accountcode", String.valueOf(accountcode));
		}
        query.executeUpdate();  
    }
    
    public void setStatus(String uniqueid, Boolean status){
    	System.out.println("IDX "+uniqueid);
    	String sql = "UPDATE Cdr e SET e.billed = :status  WHERE e.uniqueid = :uniqueid";
    	Query query = em.createQuery(sql);
    	query.setParameter("status", status);
    	query.setParameter("uniqueid", uniqueid);
        query.executeUpdate();  
    }

    @SuppressWarnings("unchecked")
    public List<Cdr> listForReprocess(Integer size) {
    	Query query = em.createQuery("SELECT e FROM Cdr e WHERE e.billed = :status" );
    	query.setParameter("status", null);
    	query.setMaxResults(size);
    	return query.getResultList();   
    }
    
    
}

